package com.puer.interceptor;

import com.puer.common.Code;
import com.puer.exception.BusinessException;
import com.puer.utils.Jwt;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private Jwt jwt;

    // 原始方法调用前执行的内容
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("----------");
        System.out.println(request.getRequestURI());
        // 通过options请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        // 图片的请求不做token检查
//        if (request.getRequestURI().contains("/images")) {
//            return true;
//        }
//        if (request.getRequestURI().contains("/doc.html")) {
//            return true;
//        }
        // token验证
        String token = request.getHeader(jwt.getHeader());
        // 检查字符串是否为 null 或长度是否为 0
        if (Objects.equals(token, "")) {
            token = request.getParameter(jwt.getHeader());
        }
        if (Objects.equals(token, "")) {
            throw new BusinessException(Code.BUSINESS_ERR, jwt.getHeader() + "不能为空！");
        }
        Claims claims = null;
        try {
            claims = jwt.getTokenClaim(token);
            if (claims == null || jwt.isTokenExpired(claims.getExpiration())) {
                throw new BusinessException(Code.BUSINESS_ERR, jwt.getHeader() + "已失效！");
            }
        } catch (Exception e) {
            throw new BusinessException(Code.BUSINESS_ERR, jwt.getHeader() + "失效，请重新登录！");
        }
        request.setAttribute("identityId", claims.getSubject());
        return true;
    }
}
